package cn.jbolt.ai.core.embedding;


import cn.jbolt.ai.resource.embedding.entity.EmbeddingResource;
import cn.jbolt.util.Result;
import com.jboltai.capability.embedding.JBoltEmbedding;
import com.jboltai.event.embedding.EmbeddingEvent;
import com.jboltai.resource.embedding.EmbeddingModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class EmbeddingServiceImpl implements EmbeddingService {

    private static final Logger logger = LoggerFactory.getLogger(EmbeddingServiceImpl.class);


    public Result embeddingText(EmbeddingModel embeddingModel, String text) {
        try {
            EmbeddingEvent event = JBoltEmbedding.embedding(embeddingModel, text);
            event.publish().await();
            if (event.isFail()) {
                logger.error("EmbeddingResource向量化失败,内容为:{},失败原因:{}", text, event.getError().getMsg());
                return Result.error(event.getError().getMsg());
            } else {
                return Result.success(event.getResult().get(0));
            }
        } catch (Exception e) {
            logger.error("EmbeddingResource向量化失败,内容为:{},失败原因:{}", text, e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result embeddingText(String embeddingResourceId, String text) {
        try {
            EmbeddingEvent event = JBoltEmbedding.embedding(embeddingResourceId, text);
            event.publish().await();
            if (event.isFail()) {
                logger.error("EmbeddingResource向量化失败,内容为:{},失败原因:{}", text, event.getError().getMsg());
                return Result.error(event.getError().getMsg());
            } else {
                return Result.success(event.getResult().get(0));
            }
        } catch (Exception e) {
            logger.error("EmbeddingResource向量化失败,内容为:{},失败原因:{}", text, e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result getModelDimension(EmbeddingModel embeddingModel, EmbeddingResource embeddingResource) {

        Integer size = 0;
        EmbeddingEvent embeddingEvent = JBoltEmbedding.embedding(embeddingModel, "测试");
        embeddingEvent.publish().await();
        if (embeddingEvent.isFail()) {
            logger.error("Embedding资源--{}-{}---获取维度失败,失败原因:{}", embeddingResource.getType(), embeddingResource.getDefaultModel(), embeddingEvent.getError().getMsg());
            return Result.error("获取维度失败");
        } else {
            size = embeddingEvent.getResult().get(0).size();
            logger.info("Embedding资源--{}-{}---获取维度成功,维度为:{}", embeddingResource.getType(), embeddingResource.getDefaultModel(), size);
            return Result.success(size);
        }

    }
}
